from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
from datetime import timedelta, datetime
import os
from functools import wraps
import jwt
from werkzeug.utils import secure_filename
from dotenv import load_dotenv

app = Flask(__name__)

# 配置CORS
app.config['CORS_HEADERS'] = 'Content-Type'
CORS(app, 
     resources={r"/*": {
         "origins": ["http://localhost:5173"],
         "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
         "allow_headers": ["Content-Type", "Authorization", "Accept", "Origin", "X-Requested-With"],
         "expose_headers": ["Content-Type", "Authorization"],
         "supports_credentials": True,
         "max_age": 3600,
         "send_wildcard": False
     }}
)

# 添加全局错误处理
@app.after_request
def after_request(response):
    response.headers.add('Access-Control-Allow-Origin', 'http://localhost:5173')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    response.headers.add('Access-Control-Allow-Credentials', 'true')
    return response

# 配置上传文件
UPLOAD_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'uploads')
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv'}
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024  # 50MB 支持视频文件

# 确保上传目录存在
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

# 加载环境变量
load_dotenv()

# 从环境变量读取数据库配置，如果没有则使用默认值
DB_USER = os.getenv('DB_USER', 'root')
# 之前默认密码 root1234 现在改为 123456 如果你本地有问题直接改为 root1234
DB_PASSWORD = os.getenv('DB_PASSWORD', '123456')
DB_HOST = os.getenv('DB_HOST', 'localhost')
DB_NAME = os.getenv('DB_NAME', 'house_rental')

# 服务器基础URL配置
SERVER_BASE_URL = os.getenv('SERVER_BASE_URL', 'http://localhost:5000')

# 媒体文件URL处理函数
def get_full_media_url(media_path):
    """
    将相对路径转换为完整的媒体文件URL
    """
    if not media_path:
        return None
    
    # 如果已经是完整URL，直接返回
    if media_path.startswith('http'):
        return media_path
    
    # 如果是相对路径，添加服务器前缀
    if media_path.startswith('/'):
        return f"{SERVER_BASE_URL}{media_path}"
    else:
        return f"{SERVER_BASE_URL}/{media_path}"

def process_house_attachments(attachments):
    """
    处理房源附件列表，将所有文件路径转换为完整URL
    """
    if not attachments:
        return []
    
    return [get_full_media_url(file) for file in attachments if file]

# 配置数据库
app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}/{DB_NAME}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'your-secret-key'  # 用于JWT加密
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(days=1)

db = SQLAlchemy(app)
jwt = JWTManager(app)

# 用户模型
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password = db.Column(db.String(120), nullable=False)
    phone = db.Column(db.String(20))
    role = db.Column(db.String(20), default='tenant')  # tenant, landlord, admin
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    def check_password(self, password):
        return self.password == password  # 实际应用中应该使用加密密码
        
    def set_password(self, password):
        self.password = password  # 实际应用中应该加密存储

# 房源模型
class House(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    description = db.Column(db.Text)
    price = db.Column(db.Float, nullable=False)
    area = db.Column(db.String(50))
    type = db.Column(db.String(20))  # 户型
    address = db.Column(db.String(200))
    # 新增省市字段
    province_id = db.Column(db.Integer, db.ForeignKey('province.id'), nullable=True)
    city_id = db.Column(db.Integer, db.ForeignKey('city.id'), nullable=True)
    status = db.Column(db.String(20), default='available')  # available, rented
    landlord_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    images = db.Column(db.JSON)  # 存储图片URL列表
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 建立关联关系
    province = db.relationship('Province', backref='houses', lazy=True)
    city = db.relationship('City', backref='houses', lazy=True)

# 租赁记录模型
class Rental(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    house_id = db.Column(db.Integer, db.ForeignKey('house.id'))
    tenant_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    start_date = db.Column(db.DateTime, nullable=False)
    end_date = db.Column(db.DateTime, nullable=False)
    status = db.Column(db.String(20), default='active')  # active, completed, cancelled
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

# 消息模型
class News(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)  # 修改为user_id
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

# 省份模型
class Province(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False, unique=True)
    code = db.Column(db.String(10), unique=True)  # 省份编码
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    
    # 关联城市
    cities = db.relationship('City', backref='province', lazy=True, cascade='all, delete-orphan')

# 城市模型
class City(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    code = db.Column(db.String(10))  # 城市编码
    province_id = db.Column(db.Integer, db.ForeignKey('province.id'), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

# 省市数据初始化函数
def init_province_city_data():
    """初始化省市数据"""
    print("开始初始化省市数据...")
    
    # 检查是否已有数据
    if Province.query.count() > 0:
        print("省市数据已存在，跳过初始化")
        return
    
    # 省市数据
    province_city_data = {
        '北京市': ['东城区', '西城区', '朝阳区', '丰台区', '石景山区', '海淀区', '门头沟区', '房山区', '通州区', '顺义区', '昌平区', '大兴区', '怀柔区', '平谷区', '密云区', '延庆区'],
        '上海市': ['黄浦区', '徐汇区', '长宁区', '静安区', '普陀区', '虹口区', '杨浦区', '闵行区', '宝山区', '嘉定区', '浦东新区', '金山区', '松江区', '青浦区', '奉贤区', '崇明区'],
        '天津市': ['和平区', '河东区', '河西区', '南开区', '河北区', '红桥区', '东丽区', '西青区', '津南区', '北辰区', '武清区', '宝坻区', '滨海新区', '宁河区', '静海区', '蓟州区'],
        '重庆市': ['万州区', '涪陵区', '渝中区', '大渡口区', '江北区', '沙坪坝区', '九龙坡区', '南岸区', '北碚区', '綦江区', '大足区', '渝北区', '巴南区', '黔江区', '长寿区', '江津区'],
        '广东省': ['广州市', '深圳市', '珠海市', '汕头市', '佛山市', '韶关市', '湛江市', '肇庆市', '江门市', '茂名市', '惠州市', '梅州市', '汕尾市', '河源市', '阳江市', '清远市', '东莞市', '中山市', '潮州市', '揭阳市', '云浮市'],
        '浙江省': ['杭州市', '宁波市', '温州市', '嘉兴市', '湖州市', '绍兴市', '金华市', '衢州市', '舟山市', '台州市', '丽水市'],
        '江苏省': ['南京市', '无锡市', '徐州市', '常州市', '苏州市', '南通市', '连云港市', '淮安市', '盐城市', '扬州市', '镇江市', '泰州市', '宿迁市'],
        '山东省': ['济南市', '青岛市', '淄博市', '枣庄市', '东营市', '烟台市', '潍坊市', '济宁市', '泰安市', '威海市', '日照市', '滨州市', '德州市', '聊城市', '临沂市', '菏泽市'],
        '河南省': ['郑州市', '开封市', '洛阳市', '平顶山市', '安阳市', '鹤壁市', '新乡市', '焦作市', '濮阳市', '许昌市', '漯河市', '三门峡市', '南阳市', '商丘市', '信阳市', '周口市', '驻马店市', '济源市'],
        '河北省': ['石家庄市', '唐山市', '秦皇岛市', '邯郸市', '邢台市', '保定市', '张家口市', '承德市', '沧州市', '廊坊市', '衡水市'],
        '湖北省': ['武汉市', '黄石市', '十堰市', '宜昌市', '襄阳市', '鄂州市', '荆门市', '孝感市', '荆州市', '黄冈市', '咸宁市', '随州市', '恩施州', '仙桃市', '潜江市', '天门市', '神农架林区'],
        '湖南省': ['长沙市', '株洲市', '湘潭市', '衡阳市', '邵阳市', '岳阳市', '常德市', '张家界市', '益阳市', '郴州市', '永州市', '怀化市', '娄底市', '湘西州'],
        '四川省': ['成都市', '自贡市', '攀枝花市', '泸州市', '德阳市', '绵阳市', '广元市', '遂宁市', '内江市', '乐山市', '南充市', '眉山市', '宜宾市', '广安市', '达州市', '雅安市', '巴中市', '资阳市', '阿坝州', '甘孜州', '凉山州'],
        '福建省': ['福州市', '厦门市', '莆田市', '三明市', '泉州市', '漳州市', '南平市', '龙岩市', '宁德市'],
        '安徽省': ['合肥市', '芜湖市', '蚌埠市', '淮南市', '马鞍山市', '淮北市', '铜陵市', '安庆市', '黄山市', '滁州市', '阜阳市', '宿州市', '六安市', '亳州市', '池州市', '宣城市'],
        '江西省': ['南昌市', '景德镇市', '萍乡市', '九江市', '新余市', '鹰潭市', '赣州市', '吉安市', '宜春市', '抚州市', '上饶市'],
        '辽宁省': ['沈阳市', '大连市', '鞍山市', '抚顺市', '本溪市', '丹东市', '锦州市', '营口市', '阜新市', '辽阳市', '盘锦市', '铁岭市', '朝阳市', '葫芦岛市'],
        '黑龙江省': ['哈尔滨市', '齐齐哈尔市', '鸡西市', '鹤岗市', '双鸭山市', '大庆市', '伊春市', '佳木斯市', '七台河市', '牡丹江市', '黑河市', '绥化市', '大兴安岭地区'],
        '陕西省': ['西安市', '铜川市', '宝鸡市', '咸阳市', '渭南市', '延安市', '汉中市', '榆林市', '安康市', '商洛市'],
        '山西省': ['太原市', '大同市', '阳泉市', '长治市', '晋城市', '朔州市', '晋中市', '运城市', '忻州市', '临汾市', '吕梁市'],
        '吉林省': ['长春市', '吉林市', '四平市', '辽源市', '通化市', '白山市', '松原市', '白城市', '延边州'],
        '甘肃省': ['兰州市', '嘉峪关市', '金昌市', '白银市', '天水市', '武威市', '张掖市', '平凉市', '酒泉市', '庆阳市', '定西市', '陇南市', '临夏州', '甘南州'],
        '云南省': ['昆明市', '曲靖市', '玉溪市', '保山市', '昭通市', '丽江市', '普洱市', '临沧市', '楚雄州', '红河州', '文山州', '西双版纳州', '大理州', '德宏州', '怒江州', '迪庆州'],
        '内蒙古自治区': ['呼和浩特市', '包头市', '乌海市', '赤峰市', '通辽市', '鄂尔多斯市', '呼伦贝尔市', '巴彦淖尔市', '乌兰察布市', '兴安盟', '锡林郭勒盟', '阿拉善盟'],
        '新疆维吾尔自治区': ['乌鲁木齐市', '克拉玛依市', '吐鲁番市', '哈密市', '昌吉州', '博尔塔拉州', '巴音郭楞州', '阿克苏地区', '克孜勒苏州', '喀什地区', '和田地区', '伊犁州', '塔城地区', '阿勒泰地区', '石河子市', '阿拉尔市', '图木舒克市', '五家渠市', '北屯市', '铁门关市', '双河市', '可克达拉市', '昆玉市', '胡杨河市'],
        '西藏自治区': ['拉萨市', '日喀则市', '昌都市', '林芝市', '山南市', '那曲市', '阿里地区'],
        '广西壮族自治区': ['南宁市', '柳州市', '桂林市', '梧州市', '北海市', '防城港市', '钦州市', '贵港市', '玉林市', '百色市', '贺州市', '河池市', '来宾市', '崇左市'],
        '宁夏回族自治区': ['银川市', '石嘴山市', '吴忠市', '固原市', '中卫市'],
        '青海省': ['西宁市', '海东市', '海北州', '黄南州', '海南州', '果洛州', '玉树州', '海西州'],
        '贵州省': ['贵阳市', '六盘水市', '遵义市', '安顺市', '毕节市', '铜仁市', '黔西南州', '黔东南州', '黔南州'],
        '海南省': ['海口市', '三亚市', '三沙市', '儋州市', '五指山市', '琼海市', '文昌市', '万宁市', '东方市', '定安县', '屯昌县', '澄迈县', '临高县', '白沙县', '昌江县', '乐东县', '陵水县', '保亭县', '琼中县'],
        '香港特别行政区': ['中西区', '湾仔区', '东区', '南区', '油尖旺区', '深水埗区', '九龙城区', '黄大仙区', '观塘区', '荃湾区', '屯门区', '元朗区', '北区', '大埔区', '沙田区', '西贡区', '葵青区', '离岛区'],
        '澳门特别行政区': ['花地玛堂区', '圣安多尼堂区', '大堂区', '望德堂区', '风顺堂区', '嘉模堂区', '圣方济各堂区', '路氹城']
    }
    
    try:
        # 添加省份和城市
        for province_name, cities in province_city_data.items():
            # 创建省份
            province = Province(
                name=province_name,
                code=f"P{len(Province.query.all()) + 1:02d}"
            )
            db.session.add(province)
            db.session.flush()  # 获取省份ID
            
            # 添加该省份的城市
            for city_name in cities:
                city = City(
                    name=city_name,
                    code=f"C{len(City.query.all()) + 1:03d}",
                    province_id=province.id
                )
                db.session.add(city)
        
        db.session.commit()
        print(f"省市数据初始化完成！共初始化 {len(province_city_data)} 个省份")
        
    except Exception as e:
        print(f"省市数据初始化失败: {str(e)}")
        db.session.rollback()

# 初始化数据库
with app.app_context():
    try:
        # 创建所有表
        db.create_all()
        print("数据库连接成功！")
        print("数据库表创建成功！")
        
        # 获取所有表名
        inspector = db.inspect(db.engine)
        tables = inspector.get_table_names()
        print("已创建的表:", tables)
        
        # 检查是否已存在管理员用户
        admin = User.query.filter_by(username='admin').first()
        if not admin:
            # 创建管理员用户
            admin = User(
                username='admin',
                password='admin123',
                role='admin',
                created_at=datetime.utcnow()
            )
            db.session.add(admin)
            db.session.commit()
            print("管理员用户创建成功！")
        
        # 初始化省市数据
        init_province_city_data()
        
    except Exception as e:
        print("数据库配置错误:", str(e))

# JWT token验证装饰器
def token_required(f):
    @wraps(f)
    @jwt_required()
    def decorated(*args, **kwargs):
        try:
            current_user_id = get_jwt_identity()
            current_user = User.query.get(current_user_id)
            if not current_user:
                return jsonify({'message': 'User not found!'}), 401
            return f(current_user, *args, **kwargs)
        except Exception as e:
            print("Token verification error:", str(e))
            return jsonify({'message': 'Token is invalid!'}), 401
    return decorated

# 角色验证装饰器
def role_required(roles):
    def decorator(f):
        @wraps(f)
        @jwt_required()
        def decorated(*args, **kwargs):
            current_user_id = get_jwt_identity()
            current_user = User.query.get(current_user_id)
            if not current_user:
                return jsonify({'message': 'User not found!'}), 401
            if current_user.role not in roles:
                return jsonify({'message': 'Permission denied!'}), 403
            return f(*args, **kwargs)
        return decorated
    return decorator

# 用户注册
@app.route('/api/register', methods=['POST'])
def register():
    try:
        data = request.get_json()
        print("Register attempt:", data)  # 添加日志
        
        if not data or not data.get('username') or not data.get('password'):
            return jsonify({'message': '请提供用户名和密码'}), 400
            
        # 检查用户名是否已存在
        existing_user = User.query.filter_by(username=data['username']).first()
        if existing_user:
            return jsonify({'message': '用户名已存在'}), 400
        
        # 创建新用户
        new_user = User(
            username=data['username'],
            password=data['password'],
            phone=data.get('phone', ''),
            role=data.get('role', 'tenant')
        )
        
        print("Creating new user:", new_user.username, new_user.role)  # 添加日志
        
        try:
            db.session.add(new_user)
            db.session.commit()
            print("User created successfully:", new_user.id)  # 添加日志
            
            # 验证用户是否真的创建成功
            created_user = User.query.filter_by(username=data['username']).first()
            if created_user:
                print("Verified user in database:", created_user.id, created_user.username)
            else:
                print("Warning: User not found in database after creation!")
            
            return jsonify({'message': '注册成功'}), 201
        except Exception as db_error:
            print("Database error during user creation:", str(db_error))
            db.session.rollback()
            return jsonify({'message': '注册失败：数据库错误'}), 500
            
    except Exception as e:
        print("Registration error:", str(e))  # 添加错误日志
        return jsonify({'message': '注册失败：服务器错误'}), 500

# 用户登录
@app.route('/api/login', methods=['POST'])
def login():
    try:
        data = request.get_json()
        print("Login attempt:", data)  # 添加日志
        
        if not data or not data.get('username') or not data.get('password'):
            return jsonify({'message': '请提供用户名和密码'}), 400
            
        # 查询用户
        user = User.query.filter_by(username=data['username']).first()
        print(user)
        print("Found user:", user.username if user else None)  # 添加日志
        
        if not user:
            return jsonify({'message': '用户不存在'}), 401
            
        # 验证密码
        if not user.check_password(data['password']):
            return jsonify({'message': '密码错误'}), 401
        
        # 生成token
        token = create_access_token(
            identity=user.id,
            additional_claims={'role': user.role},
            expires_delta=timedelta(days=1)
        )
        
        print("Login successful for user:", user.username)  # 添加日志
        
        return jsonify({
            'token': token,
            'role': user.role,
            'message': '登录成功'
        })
    except Exception as e:
        print("Login error:", str(e))  # 添加错误日志
        return jsonify({'message': '登录失败'}), 500

# 获取用户列表（管理员）
@app.route('/api/users', methods=['GET'])
@jwt_required()
@role_required(['admin'])
def get_users():
    users = User.query.all()
    return jsonify([{
        'id': user.id,
        'username': user.username,
        'phone': user.phone,
        'role': user.role,
        'created_at': user.created_at
    } for user in users])

# 删除用户（管理员）
@app.route('/api/users/<int:user_id>', methods=['DELETE'])
@jwt_required()
@role_required(['admin'])
def delete_user(user_id):
    user = User.query.get_or_404(user_id)
    db.session.delete(user)
    db.session.commit()
    return jsonify({'message': 'User deleted successfully!'})

# 发布房源（房东）
@app.route('/api/houses', methods=['POST'])
@token_required
@role_required(['landlord'])
def create_house(current_user):
    data = request.get_json()
    
    # 验证省市字段
    province_id = data.get('province_id')
    city_id = data.get('city_id')
    
    # 如果提供了省市ID，验证其有效性
    if province_id:
        province = Province.query.get(province_id)
        if not province:
            return jsonify({'message': '省份不存在'}), 400
    
    if city_id:
        city = City.query.get(city_id)
        if not city:
            return jsonify({'message': '城市不存在'}), 400
        # 验证城市是否属于指定省份
        if province_id and city.province_id != province_id:
            return jsonify({'message': '城市与省份不匹配'}), 400
    
    new_house = House(
        title=data['title'],
        description=data['description'],
        price=data['price'],
        area=data['area'],
        type=data['type'],
        address=data['address'],
        province_id=province_id,
        city_id=city_id,
        landlord_id=current_user.id,
        images=data.get('images', [])
    )
    db.session.add(new_house)
    db.session.commit()
    return jsonify({'message': 'House created successfully!'}), 201

# 获取房源列表
@app.route('/api/houses', methods=['GET'])
@jwt_required()
def get_houses():
    try:
        houses = House.query.all()
        return jsonify([{
            'id': house.id,
            'title': house.title,
            'description': house.description,
            'price': house.price,
            'area': house.area,
            'type': house.type,
            'address': house.address,
            'province_id': house.province_id,
            'city_id': house.city_id,
            'province_name': house.province.name if house.province else None,
            'city_name': house.city.name if house.city else None,
            'status': house.status,
            'landlord_id': house.landlord_id,
            'images': process_house_attachments(house.images),
            'created_at': house.created_at.strftime('%Y-%m-%d %H:%M:%S')
        } for house in houses])
    except Exception as e:
        print(f"获取房源列表失败: {str(e)}")
        return jsonify({'error': f'获取房源列表失败: {str(e)}'}), 500

# 智能搜索 - 按地区搜索（支持省市级联）
@app.route('/api/houses/search/region', methods=['GET'])
@jwt_required()
def search_houses_by_region():
    # 获取查询参数
    province_id = request.args.get('province_id', type=int)
    city_id = request.args.get('city_id', type=int)
    region = request.args.get('region', '')  # 详细地区（原有的模糊搜索）
    
    print(f"🔍 地区搜索参数: province_id={province_id}, city_id={city_id}, region='{region}'")
    
    # 验证参数
    if not province_id and not city_id and not region:
        return jsonify({'message': '请提供省份ID、城市ID或详细地区名称'}), 400
    
    try:
        # 构建查询
        query = House.query.filter(House.status == 'available')
        search_description = []
        
        # 按省份查询
        if province_id:
            province = Province.query.get(province_id)
            if not province:
                return jsonify({'message': '省份不存在'}), 404
            
            query = query.filter(House.province_id == province_id)
            search_description.append(f"省份: {province.name}")
            print(f"📍 添加省份筛选: {province.name}")
        
        # 按城市查询
        if city_id:
            city = City.query.get(city_id)
            if not city:
                return jsonify({'message': '城市不存在'}), 404
            
            query = query.filter(House.city_id == city_id)
            search_description.append(f"城市: {city.name}")
            print(f"🏙️ 添加城市筛选: {city.name}")
            
            # 如果同时提供了省份和城市，验证城市是否属于该省份
            if province_id and city.province_id != province_id:
                return jsonify({'message': '城市与省份不匹配'}), 400
        
        # 按详细地区模糊搜索（address字段）
        if region:
            query = query.filter(House.address.ilike(f'%{region}%'))
            search_description.append(f"地区关键词: {region}")
            print(f"🔍 添加地区模糊搜索: {region}")
        
        # 执行查询
        houses = query.all()
        total_count = len(houses)
        
        print(f"✅ 地区搜索结果: 找到 {total_count} 套房源")
        
        # 构建搜索描述
        search_info = " + ".join(search_description) if search_description else "全部地区"
        
        result = {
            'search_info': search_info,
            'search_params': {
                'province_id': province_id,
                'city_id': city_id,
                'region': region
            },
            'total_count': total_count,
            'houses': [{
                'id': house.id,
                'title': house.title,
                'description': house.description,
                'price': house.price,
                'area': house.area,
                'type': house.type,
                'address': house.address,
                'province_id': house.province_id,
                'city_id': house.city_id,
                'province_name': house.province.name if house.province else None,
                'city_name': house.city.name if house.city else None,
                'status': house.status,
                'landlord_id': house.landlord_id,
                'images': process_house_attachments(house.images),
                'created_at': house.created_at.strftime('%Y-%m-%d %H:%M:%S')
            } for house in houses]
        }
        
        return jsonify(result)
        
    except Exception as e:
        print(f"地区搜索失败: {str(e)}")
        return jsonify({'error': f'地区搜索失败: {str(e)}'}), 500

# 智能搜索 - 按户型搜索
@app.route('/api/houses/search/type', methods=['GET'])
@jwt_required()
def search_houses_by_type():
    house_type = request.args.get('type', '')
    if not house_type:
        return jsonify({'message': '请提供搜索的户型'}), 400
    
    # 构建查询
    query = House.query.filter(House.status == 'available')
    
    if house_type:
        # 如果是简单数字格式，使用精确匹配
        if house_type.isdigit():
            query = query.filter(House.type == house_type)
            print(f"🏠 添加户型精确筛选: = {house_type}")
        else:
            # 如果是完整格式，使用模糊匹配
            query = query.filter(House.type.ilike(f'%{house_type}%'))
            print(f"🏠 添加户型模糊筛选: {house_type}")
    
    houses = query.all()
    total_count = len(houses)
    
    result = {
        'type': house_type,
        'total_count': total_count,
        'houses': [{
            'id': house.id,
            'title': house.title,
            'description': house.description,
            'price': house.price,
            'area': house.area,
            'type': house.type,
            'address': house.address,
            'status': house.status,
            'landlord_id': house.landlord_id,
            'images': process_house_attachments(house.images),  # 处理图片URL
            'created_at': house.created_at.strftime('%Y-%m-%d %H:%M:%S')
        } for house in houses]
    }
    
    return jsonify(result)

# 综合搜索 - 支持多条件搜索
@app.route('/api/houses/search', methods=['GET'])
@jwt_required()
def search_houses():
    # 获取搜索参数
    region = request.args.get('region', '')
    house_type = request.args.get('type', '')
    min_price = request.args.get('min_price', type=float)
    max_price = request.args.get('max_price', type=float)
    min_area = request.args.get('min_area', '')
    max_area = request.args.get('max_area', '')
    
    # 调试信息
    print("🔍 搜索参数:", {
        'region': region,
        'type': house_type,
        'min_price': min_price,
        'max_price': max_price,
        'min_area': min_area,
        'max_area': max_area
    })
    
    # 构建查询
    query = House.query.filter(House.status == 'available')
    
    if region:
        query = query.filter(House.address.ilike(f'%{region}%'))
        print(f"📍 添加地区筛选: {region}")
    
    if house_type:
        # 如果是简单数字格式，使用精确匹配
        if house_type.isdigit():
            query = query.filter(House.type == house_type)
            print(f"🏠 添加户型精确筛选: = {house_type}")
        else:
            # 如果是完整格式，使用模糊匹配
            query = query.filter(House.type.ilike(f'%{house_type}%'))
            print(f"🏠 添加户型模糊筛选: {house_type}")
    
    if min_price is not None:
        query = query.filter(House.price >= min_price)
        print(f"💰 添加最低价格筛选: >= {min_price}")
    
    if max_price is not None:
        query = query.filter(House.price <= max_price)
        print(f"💰 添加最高价格筛选: <= {max_price}")
    
    if min_area:
        query = query.filter(House.area >= min_area)
        print(f"📐 添加最小面积筛选: >= {min_area}")
    
    if max_area:
        query = query.filter(House.area <= max_area)
        print(f"📐 添加最大面积筛选: <= {max_area}")
    
    houses = query.all()
    total_count = len(houses)
    
    print(f"✅ 筛选结果: 找到 {total_count} 套房源")
    
    result = {
        'search_params': {
            'region': region,
            'type': house_type,
            'min_price': min_price,
            'max_price': max_price,
            'min_area': min_area,
            'max_area': max_area
        },
        'total_count': total_count,
        'houses': [{
            'id': house.id,
            'title': house.title,
            'description': house.description,
            'price': house.price,
            'area': house.area,
            'type': house.type,
            'address': house.address,
            'status': house.status,
            'landlord_id': house.landlord_id,
            'images': process_house_attachments(house.images),  # 处理图片URL
            'created_at': house.created_at.strftime('%Y-%m-%d %H:%M:%S')
        } for house in houses]
    }
    
    return jsonify(result)

# 获取房源详情（智能推荐相关房源）
@app.route('/api/houses/<int:house_id>/detail', methods=['GET'])
@jwt_required()
def get_house_detail(house_id):
    house = House.query.get_or_404(house_id)
    
    # 获取房东信息
    landlord = User.query.get(house.landlord_id)
    
    # 智能推荐：相同地区或相同户型的房源
    recommended_houses = House.query.filter(
        House.id != house_id,
        House.status == 'available',
        db.or_(
            House.address.ilike(f'%{house.address.split()[0] if house.address else ""}%'),
            House.type == house.type
        )
    ).limit(5).all()
    
    result = {
        'house': {
            'id': house.id,
            'title': house.title,
            'description': house.description,
            'price': house.price,
            'area': house.area,
            'type': house.type,
            'address': house.address,
            'province_id': house.province_id,
            'city_id': house.city_id,
            'province_name': house.province.name if house.province else None,
            'city_name': house.city.name if house.city else None,
            'status': house.status,
            'images': process_house_attachments(house.images),
            'created_at': house.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'landlord': {
                'id': landlord.id,
                'username': landlord.username,
                'phone': landlord.phone
            } if landlord else None
        },
        'recommended_houses': [{
            'id': rh.id,
            'title': rh.title,
            'price': rh.price,
            'area': rh.area,
            'type': rh.type,
            'address': rh.address,
            'province_name': rh.province.name if rh.province else None,
            'city_name': rh.city.name if rh.city else None,
            'images': process_house_attachments(rh.images)
        } for rh in recommended_houses]
    }
    
    return jsonify(result)

# 获取房东的房源列表
@app.route('/api/landlord/houses', methods=['GET'])
@token_required
@role_required(['landlord'])
def get_landlord_houses(current_user):
    try:
        houses = House.query.filter_by(landlord_id=current_user.id).all()
        return jsonify([{
            'id': house.id,
            'title': house.title,
            'description': house.description,
            'price': house.price,
            'area': house.area,
            'type': house.type,
            'address': house.address,
            'province_id': house.province_id,
            'city_id': house.city_id,
            'province_name': house.province.name if house.province else None,
            'city_name': house.city.name if house.city else None,
            'status': house.status,
            'images': process_house_attachments(house.images),
            'created_at': house.created_at.strftime('%Y-%m-%d %H:%M:%S')
        } for house in houses])
    except Exception as e:
        print(f"获取房东房源列表失败: {str(e)}")
        return jsonify({'error': f'获取房东房源列表失败: {str(e)}'}), 500

# 更新房源信息
@app.route('/api/houses/<int:house_id>', methods=['PUT'])
@token_required
@role_required(['landlord'])
def update_house(current_user, house_id):
    house = House.query.get_or_404(house_id)
    if house.landlord_id != current_user.id:
        return jsonify({'message': 'Permission denied!'}), 403
    
    data = request.get_json()
    
    # 验证省市字段
    if 'province_id' in data:
        province_id = data['province_id']
        if province_id:
            province = Province.query.get(province_id)
            if not province:
                return jsonify({'message': '省份不存在'}), 400
    
    if 'city_id' in data:
        city_id = data['city_id']
        if city_id:
            city = City.query.get(city_id)
            if not city:
                return jsonify({'message': '城市不存在'}), 400
            # 验证城市是否属于指定省份
            province_id = data.get('province_id', house.province_id)
            if province_id and city.province_id != province_id:
                return jsonify({'message': '城市与省份不匹配'}), 400
    
    # 更新字段
    for key, value in data.items():
        if hasattr(house, key):
            setattr(house, key, value)
    
    db.session.commit()
    return jsonify({'message': 'House updated successfully!'})

# 删除房源
@app.route('/api/houses/<int:house_id>', methods=['DELETE'])
@token_required
@role_required(['landlord'])
def delete_house(current_user, house_id):
    house = House.query.get_or_404(house_id)
    if house.landlord_id != current_user.id:
        return jsonify({'message': 'Permission denied!'}), 403
    
    db.session.delete(house)
    db.session.commit()
    return jsonify({'message': 'House deleted successfully!'})

# 更新房源状态
@app.route('/api/houses/<int:house_id>/status', methods=['PUT'])
@token_required
@role_required(['landlord', 'admin'])
def update_house_status(current_user, house_id):
    house = House.query.get_or_404(house_id)
    
    # 检查权限：房东只能管理自己的房源，管理员可以管理所有房源
    if current_user.role == 'landlord' and house.landlord_id != current_user.id:
        return jsonify({'message': 'Permission denied!'}), 403
    
    data = request.get_json()
    new_status = data.get('status')
    
    # 定义允许的状态
    allowed_statuses = ['available', 'rented', 'maintenance', 'unavailable']
    
    if not new_status or new_status not in allowed_statuses:
        return jsonify({
            'message': f'无效的状态。允许的状态: {", ".join(allowed_statuses)}'
        }), 400
    
    old_status = house.status
    house.status = new_status
    db.session.commit()
    
    return jsonify({
        'message': f'房源状态已从 {old_status} 更新为 {new_status}',
        'house_id': house_id,
        'old_status': old_status,
        'new_status': new_status
    })

# 获取房源状态统计
@app.route('/api/houses/statistics', methods=['GET'])
@jwt_required()
@role_required(['landlord', 'admin'])
def get_house_statistics():
    # 总体统计
    total_houses = House.query.count()
    available_houses = House.query.filter_by(status='available').count()
    rented_houses = House.query.filter_by(status='rented').count()
    maintenance_houses = House.query.filter_by(status='maintenance').count()
    unavailable_houses = House.query.filter_by(status='unavailable').count()
    
    result = {
        'total_houses': total_houses,
        'status_breakdown': {
            'available': available_houses,
            'rented': rented_houses,
            'maintenance': maintenance_houses,
            'unavailable': unavailable_houses
        },
        'occupancy_rate': round((rented_houses / total_houses * 100), 2) if total_houses > 0 else 0
    }
    
    return jsonify(result)

# 发布消息（所有用户）
@app.route('/api/news', methods=['POST'])
@token_required
def create_news(current_user):
    data = request.get_json()
    new_news = News(
        title=data['title'],
        content=data['content'],
        user_id=current_user.id  # 使用当前用户ID
    )
    db.session.add(new_news)
    db.session.commit()
    return jsonify({'message': 'News created successfully!'}), 201

# 获取消息列表
@app.route('/api/news', methods=['GET'])
@token_required
def get_news(current_user):
    search_query = request.args.get('q', '')
    query = News.query
    
    if search_query:
        query = query.filter(
            db.or_(
                News.title.ilike(f'%{search_query}%'),
                News.content.ilike(f'%{search_query}%')
            )
        )
    
    news = query.order_by(News.created_at.desc()).all()
    return jsonify([{
        'id': item.id,
        'title': item.title,
        'content': item.content,
        'user_id': item.user_id,
        'username': User.query.get(item.user_id).username,  # 添加用户名
        'created_at': item.created_at.strftime('%Y-%m-%d %H:%M:%S')
    } for item in news])

# 允许的文件类型
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def get_file_type(filename):
    """判断文件类型"""
    ext = filename.rsplit('.', 1)[1].lower() if '.' in filename else ''
    if ext in {'png', 'jpg', 'jpeg', 'gif'}:
        return 'image'
    elif ext in {'mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv'}:
        return 'video'
    else:
        return 'unknown'

# 文件上传接口
@app.route('/api/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': '没有文件'}), 400
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': '没有选择文件'}), 400
    
    if file and allowed_file(file.filename):
        # 生成安全的文件名
        filename = secure_filename(file.filename)
        # 添加时间戳和用户ID到文件名
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        unique_filename = f"{timestamp}_{filename}"
        
        # 保存文件
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
        file.save(file_path)
        
        # 获取文件类型
        file_type = get_file_type(filename)
        
        # 返回完整的文件URL和类型信息
        full_url = get_full_media_url(f'/uploads/{unique_filename}')
        return jsonify({
            'url': full_url,
            'filename': unique_filename,
            'type': file_type,
            'original_name': filename
        })
    
    return jsonify({'error': '不支持的文件类型'}), 400

# 添加静态文件服务
@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

# 更新消息
@app.route('/api/news/<int:news_id>', methods=['PUT'])
@token_required
def update_news(current_user, news_id):
    news = News.query.get_or_404(news_id)
    if news.user_id != current_user.id:
        return jsonify({'message': 'Unauthorized'}), 403
    
    data = request.get_json()
    news.title = data['title']
    news.content = data['content']
    db.session.commit()
    return jsonify({'message': 'News updated successfully!'})

# 删除消息
@app.route('/api/news/<int:news_id>', methods=['DELETE'])
@token_required
def delete_news(current_user, news_id):
    news = News.query.get_or_404(news_id)
    if news.user_id != current_user.id:
        return jsonify({'message': 'Unauthorized'}), 403
    
    db.session.delete(news)
    db.session.commit()
    return jsonify({'message': 'News deleted successfully!'})

# 健康检查端点
@app.route('/health', methods=['GET'])
def health_check():
    """
    健康检查端点，用于检查服务是否正常运行
    """
    return jsonify({
        'status': 'healthy',
        'server': SERVER_BASE_URL,
        'timestamp': datetime.now().isoformat(),
        'version': '1.0.0'
    })

# 调试接口 - 查看所有房源信息
@app.route('/api/debug/houses', methods=['GET'])
@jwt_required()
def debug_houses():
    """
    调试接口，显示数据库中所有房源的详细信息
    """
    houses = House.query.all()
    result = {
        'total_count': len(houses),
        'houses': [{
            'id': house.id,
            'title': house.title,
            'price': house.price,
            'area': house.area,
            'type': house.type,
            'address': house.address,
            'status': house.status,
            'landlord_id': house.landlord_id,
            'created_at': house.created_at.strftime('%Y-%m-%d %H:%M:%S')
        } for house in houses]
    }
    
    print("📊 数据库中的房源信息:")
    for house in houses:
        print(f"  ID: {house.id}, 标题: {house.title}, 价格: {house.price}, 户型: {house.type}, 状态: {house.status}")
    
    return jsonify(result)

# ==================== 省市级联选择器 API ====================

# 获取所有省份列表
@app.route('/api/provinces', methods=['GET'])
def get_provinces():
    """
    获取所有省份列表
    """
    try:
        provinces = Province.query.order_by(Province.name).all()
        result = [{
            'id': province.id,
            'name': province.name,
            'code': province.code,
            'city_count': len(province.cities)
        } for province in provinces]
        
        return jsonify({
            'provinces': result,
            'total_count': len(result)
        })
    except Exception as e:
        return jsonify({'error': f'获取省份列表失败: {str(e)}'}), 500

# 根据省份ID获取城市列表
@app.route('/api/provinces/<int:province_id>/cities', methods=['GET'])
def get_cities_by_province(province_id):
    """
    根据省份ID获取该省份下的所有城市
    """
    try:
        province = Province.query.get_or_404(province_id)
        cities = City.query.filter_by(province_id=province_id).order_by(City.name).all()
        
        result = [{
            'id': city.id,
            'name': city.name,
            'code': city.code,
            'province_id': city.province_id,
            'province_name': province.name
        } for city in cities]
        
        return jsonify({
            'province': {
                'id': province.id,
                'name': province.name,
                'code': province.code
            },
            'cities': result,
            'total_count': len(result)
        })
    except Exception as e:
        return jsonify({'error': f'获取城市列表失败: {str(e)}'}), 500

# 根据省份名称获取城市列表
@app.route('/api/provinces/<string:province_name>/cities', methods=['GET'])
def get_cities_by_province_name(province_name):
    """
    根据省份名称获取该省份下的所有城市
    """
    try:
        province = Province.query.filter_by(name=province_name).first()
        if not province:
            return jsonify({'error': f'省份 "{province_name}" 不存在'}), 404
        
        cities = City.query.filter_by(province_id=province.id).order_by(City.name).all()
        
        result = [{
            'id': city.id,
            'name': city.name,
            'code': city.code,
            'province_id': city.province_id,
            'province_name': province.name
        } for city in cities]
        
        return jsonify({
            'province': {
                'id': province.id,
                'name': province.name,
                'code': province.code
            },
            'cities': result,
            'total_count': len(result)
        })
    except Exception as e:
        return jsonify({'error': f'获取城市列表失败: {str(e)}'}), 500

# 获取完整的省市级联数据
@app.route('/api/regions/cascader', methods=['GET'])
def get_regions_cascader():
    """
    获取完整的省市级联数据，适用于级联选择器组件
    """
    try:
        provinces = Province.query.order_by(Province.name).all()
        
        result = []
        for province in provinces:
            cities = City.query.filter_by(province_id=province.id).order_by(City.name).all()
            
            province_data = {
                'value': province.id,
                'label': province.name,
                'code': province.code,
                'children': [{
                    'value': city.id,
                    'label': city.name,
                    'code': city.code
                } for city in cities]
            }
            result.append(province_data)
        
        return jsonify({
            'regions': result,
            'total_provinces': len(result),
            'total_cities': sum(len(province['children']) for province in result)
        })
    except Exception as e:
        return jsonify({'error': f'获取级联数据失败: {str(e)}'}), 500

# 搜索省市
@app.route('/api/regions/search', methods=['GET'])
def search_regions():
    """
    搜索省市，支持模糊匹配
    """
    try:
        keyword = request.args.get('keyword', '').strip()
        if not keyword:
            return jsonify({'error': '请提供搜索关键词'}), 400
        
        # 搜索省份
        provinces = Province.query.filter(
            Province.name.ilike(f'%{keyword}%')
        ).all()
        
        # 搜索城市
        cities = City.query.filter(
            City.name.ilike(f'%{keyword}%')
        ).all()
        
        result = {
            'provinces': [{
                'id': province.id,
                'name': province.name,
                'code': province.code,
                'type': 'province'
            } for province in provinces],
            'cities': [{
                'id': city.id,
                'name': city.name,
                'code': city.code,
                'province_id': city.province_id,
                'province_name': city.province.name,
                'type': 'city'
            } for city in cities]
        }
        
        return jsonify({
            'keyword': keyword,
            'results': result,
            'province_count': len(result['provinces']),
            'city_count': len(result['cities'])
        })
    except Exception as e:
        return jsonify({'error': f'搜索失败: {str(e)}'}), 500

# 获取热门城市
@app.route('/api/regions/hot-cities', methods=['GET'])
def get_hot_cities():
    """
    获取热门城市列表
    """
    try:
        # 定义热门城市列表（可以根据实际业务需求调整）
        hot_city_names = [
            '北京市', '上海市', '广州市', '深圳市', '天津市', '重庆市',
            '杭州市', '南京市', '苏州市', '成都市', '武汉市', '西安市',
            '郑州市', '青岛市', '大连市', '宁波市', '厦门市', '福州市'
        ]
        
        hot_cities = []
        for city_name in hot_city_names:
            city = City.query.filter_by(name=city_name).first()
            if city:
                hot_cities.append({
                    'id': city.id,
                    'name': city.name,
                    'code': city.code,
                    'province_id': city.province_id,
                    'province_name': city.province.name
                })
        
        return jsonify({
            'hot_cities': hot_cities,
            'total_count': len(hot_cities)
        })
    except Exception as e:
        return jsonify({'error': f'获取热门城市失败: {str(e)}'}), 500

# ==================== 省市数据管理 API (管理员) ====================

# 添加省份 (管理员)
@app.route('/api/admin/provinces', methods=['POST'])
@jwt_required()
@role_required(['admin'])
def add_province():
    """
    添加新省份 (仅管理员)
    """
    try:
        data = request.get_json()
        if not data or not data.get('name'):
            return jsonify({'error': '请提供省份名称'}), 400
        
        # 检查省份是否已存在
        existing_province = Province.query.filter_by(name=data['name']).first()
        if existing_province:
            return jsonify({'error': '省份已存在'}), 400
        
        # 创建新省份
        new_province = Province(
            name=data['name'],
            code=data.get('code', f"P{len(Province.query.all()) + 1:02d}")
        )
        
        db.session.add(new_province)
        db.session.commit()
        
        return jsonify({
            'message': '省份添加成功',
            'province': {
                'id': new_province.id,
                'name': new_province.name,
                'code': new_province.code
            }
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'添加省份失败: {str(e)}'}), 500

# 添加城市 (管理员)
@app.route('/api/admin/cities', methods=['POST'])
@jwt_required()
@role_required(['admin'])
def add_city():
    """
    添加新城市 (仅管理员)
    """
    try:
        data = request.get_json()
        if not data or not data.get('name') or not data.get('province_id'):
            return jsonify({'error': '请提供城市名称和省份ID'}), 400
        
        # 检查省份是否存在
        province = Province.query.get(data['province_id'])
        if not province:
            return jsonify({'error': '省份不存在'}), 404
        
        # 检查城市是否已存在
        existing_city = City.query.filter_by(
            name=data['name'], 
            province_id=data['province_id']
        ).first()
        if existing_city:
            return jsonify({'error': '该省份下城市已存在'}), 400
        
        # 创建新城市
        new_city = City(
            name=data['name'],
            code=data.get('code', f"C{len(City.query.all()) + 1:03d}"),
            province_id=data['province_id']
        )
        
        db.session.add(new_city)
        db.session.commit()
        
        return jsonify({
            'message': '城市添加成功',
            'city': {
                'id': new_city.id,
                'name': new_city.name,
                'code': new_city.code,
                'province_id': new_city.province_id,
                'province_name': province.name
            }
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'添加城市失败: {str(e)}'}), 500

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    
    # 输出服务器配置信息
    print("=" * 50)
    print("🚀 Flask服务器配置信息:")
    print(f"📍 服务器地址: {SERVER_BASE_URL}")
    print(f"📂 上传目录: {UPLOAD_FOLDER}")
    print(f"🗄️  数据库: {DB_USER}@{DB_HOST}/{DB_NAME}")
    print(f"🌐 CORS允许域名: http://localhost:5173")
    print("=" * 50)
    
    app.run(debug=True)
